﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace snat.model {
    public delegate void algorithmDelegate();

    /// <summary>
    /// This node is an overlay node with a reset thingy innit.
    /// </summary>

    public class ResettableNode : OverlayNode {

        /// <summary>
        /// Adds an out edge to the overlay network when out edge is added to structural network
        /// </summary>
        /// <param name="e">Edge to add</param>
        /// <param name="n">This node</param>
        private void UpdateOverlayOutEdges(Edge e, BaseNode n) {
            if (!OverlayOutEdges.Contains(e)) OverlayOutEdges.Add(e);
        }
        /// <summary>
        /// Adds an in edge to the overlay network when in edge is added to structural network
        /// </summary>
        /// <param name="e">Edge to add</param>
        /// <param name="n">This node</param>
        private void UpdateOverlayInEdges(Edge e, BaseNode n) {
            if (!OverlayInEdges.Contains(e)) OverlayInEdges.Add(e);
        }

        private void Sent(Message m, BaseNode n) {
            foreach (BaseNode b in m.Recipients) {
                Edge existingEdge = OutEdges.Find(e => e.Target.ID == b.ID);
                if (existingEdge != null && !OverlayOutEdges.Contains(existingEdge)) {//sanity check - never not true
                    TriggerOverlayOutEdgeAdded(existingEdge);
                }
            }
        }

        private void Received(Message m, BaseNode n) {
            Edge existingEdge = InEdges.Find(e => e.Source.ID == m.Sender.ID);
            if (existingEdge != null && !OverlayInEdges.Contains(existingEdge)) {
                TriggerOverlayInEdgeAdded(existingEdge);
            }
        }

        public ResettableNode(int _id, string _name)
            : base(_id, _name) {
            MessageSend += Sent;
            MessageRecieve += Received;
            this.InEdgeAdded += UpdateOverlayInEdges;
            this.OutEdgeAdded += UpdateOverlayOutEdges;
        }
    }
}

